﻿using System;
using System.IO;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using BGM.Sensors.MeasuringDevice;
using System.Linq;
using BGM.Application.View;


namespace BloodGlucoseManagerApplication
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {

            //InitializeComponent();
        }
        PlugInManager m;
        Controller controller;
        private void Window_Initialized(object sender, EventArgs e)
        {
            MemoryStream iconStream = new MemoryStream();
            global::BloodGlucoseManagerApplication.Properties.Resources.BGM.Save(iconStream);
            iconStream.Seek(0, SeekOrigin.Begin);
            this.Icon = BitmapFrame.Create(iconStream);

            m = new PlugInManager();
                        controller = new Controller();

            LoadPlugin();
            fromDatePicker.Value = DateTime.Now.Subtract(new TimeSpan(7 * 3, 0, 0, 0, 0));

            toDatePicker.Value = DateTime.Now;


        }
        private void LoadPlugin()
        {
            Type t = typeof(IMeasuringDevice);
            m.LoadAssemblies();
            comboboxMeasurementDevices.ItemsSource = from item in m.MeasurmentsPlugins
                                                     where t.IsAssignableFrom(item.GetType())
                                                     select new { Name = item.Name, Class = item };
            comboboxMeasurementDevices.DisplayMemberPath = "Name";
            comboboxMeasurementDevices.SelectedValuePath = "Class";

            if (comboboxMeasurementDevices.Items.Count > 0)
                comboboxMeasurementDevices.SelectedIndex = 0;

            t = typeof(IDataPresenter);
            var dataPresenters = from p in m.ViewPlugins
                                 where t.IsAssignableFrom(p.GetType())
                                 select new { Name = p.Name, Class = p, Description = p.Description };
            foreach (var item in dataPresenters)
            {
                Button b = new Button();
                b.Content = item.Name;
                b.Tag = item.Class;
                b.ToolTip = item.Description;
                b.Click += new RoutedEventHandler(buttonPresentData_Click);

                dataPresenterStackPanel.Children.Add(b);
            }
        }

        private void buttonUpload_Click(object sender, RoutedEventArgs e)
        {

            var device = comboboxMeasurementDevices.SelectedValue as IMeasuringDevice;
            if (device != null)
            {
                var window = new UploadMeterWindow(device);
                
                window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
               // window.SizeToContent = SizeToContent.WidthAndHeight;
                window.ShowDialog();
                                
                controller.SaveReadings(window.Readings);
            }
               
        }

        private void buttonPresentData_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button != null)
            {
                var presenter = button.Tag as IDataPresenter;
                if (presenter != null)
                {
                    TabItem tabItem = new TabItem();
                    tabItem.Header = button.Content;
                    DockPanel p = new DockPanel();
                    p.LastChildFill = true;
                    ContentTabs.Items.Add(tabItem);
                    tabItem.Content = p;
                    ScrollViewer scroll = new ScrollViewer();
                    p.Children.Add(scroll);
                    scroll.Content = (presenter.GetPresentation(controller.SelectedPatient, controller.GetReadings(fromDatePicker.Value, toDatePicker.Value, (bool)checkOnlyCheckBox.IsChecked)));


                    ContentTabs.SelectedItem = tabItem;
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            controller.LoadPatient(this);
        }



        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            controller.Exit();
        }

        private void OpenButton_Click(object sender, RoutedEventArgs e)
        {
              controller.LoadPatient(this);
        }

        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            controller.ShowCreateNewPatient(this);
        }
        private void OnPrint(object sender, RoutedEventArgs e)
        {

            PrintDialog dlg = new PrintDialog();
            if ((bool)dlg.ShowDialog().GetValueOrDefault())
            {
                TabItem t = ((TabItem)ContentTabs.SelectedItem);
                if (t == null)
                    return;
                UserControl uc =  ((t.Content as DockPanel).Children[0] as ScrollViewer).Content as UserControl;

                if (uc == null)
                    return;

                PrintTicket prntkt = dlg.PrintTicket;
                prntkt.PageOrientation = PageOrientation.Landscape;
                prntkt.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4);
                dlg.PrintTicket = prntkt;

                //uc.BorderBrush = Brushes.Black;
                //uc.BorderThickness = new Thickness(3);
                //uc.HorizontalAlignment = HorizontalAlignment.Stretch;
                //uc.VerticalAlignment = VerticalAlignment.Stretch;
                //uc.Width = dlg.PrintableAreaWidth;
                //uc.Height = dlg.PrintableAreaHeight;
                //uc.InvalidateVisual();

                //uc.LayoutTransform = null;
                //uc.InvalidateVisual();
                //uc.
                //uc.Measure(new Size(500, 500));
                //uc.Arrange(new Rect(new Size(500, 500)));
                dlg.PrintVisual(uc, t.Header.ToString());
            }
            //PrintDocumentImageableArea area = null;

            //XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(ref area);

            //if (xpsdw != null)
            //{
            //    TabItem t=((TabItem)ContentTabs.SelectedItem);
            //    UserControl uc = (UserControl)t.Content;
            //    uc.LayoutTransform = null;
            //    // Get the size of the canvas
            //    Size size = new Size(uc.Width, uc.Height);
            //    // Measure and arrange elements
            //    //uc.Measure(size);
            //    //uc.Arrange(new Rect(size));
            //    xpsdw.Write(uc);
            //    //foreach (var item in ((Panel)uc.Content).Children)
            //    //{
            //    //   xpsdw.Write((Visual)item); 
            //    //}

            //}

        }
        public void Export(Uri path, Canvas surface)
        {
            //if (path == null) return;

            //// Save current canvas transorm
            //Transform transform = surface.LayoutTransform;
            //// Temporarily reset the layout transform before saving
            //surface.LayoutTransform = null;

            //// Get the size of the canvas
            //Size size = new Size(surface.Width, surface.Height);
            //// Measure and arrange elements
            //surface.Measure(size);
            //surface.Arrange(new Rect(size));

            //// Open new package
            //Package package = Package.Open(path.LocalPath, FileMode.Create);
            //// Create new xps document based on the package opened
            //XpsDocument doc = new XpsDocument(package);
            //// Create an instance of XpsDocumentWriter for the document
            //XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
            //// Write the canvas (as Visual) to the document
            //writer.Write(surface);
            //// Close document
            //doc.Close();
            //// Close package
            //package.Close();
        }

        private void PrintButton_Click(object sender, RoutedEventArgs e)
        {
            OnPrint(this, null);
        }

        private void ContentTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PrintButton.Header = "_Print (" + ((TabItem)ContentTabs.SelectedItem).Header + ")";

            try
            {


               canvasZoomSlider.Value= ((((ContentTabs.SelectedItem as TabItem).Content as DockPanel).Children[0] as ScrollViewer).LayoutTransform as ScaleTransform).ScaleX;
            }
            catch (Exception)
            {


            }
        }

        private void canvasZoomSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {


                (((ContentTabs.SelectedItem as TabItem).Content as DockPanel).Children[0] as ScrollViewer).LayoutTransform = new ScaleTransform(e.NewValue, e.NewValue);
            }
            catch (Exception)
            {


            }
        }



    }
}
